﻿using ORMDemo.Core.DBFilter;
using ORMDemo.Core.Mapping;
using ORMDemo.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ORMDemo.Dal
{
    public static class SqlCacheBuilder<T> where T : BaseModel, new()
    {
        private static string _findOneSql = null;
        private static string _insertOneSql = null;
        private static string _updateOneSql = null;
        private static string _deleteOneSql = null;
        static SqlCacheBuilder()
        {
            //findone
            {
                Type type = typeof(T);
                string colomn = string.Join(",", type.GetProperties().Select(p => $"[{p.GetMappingColumnName()}]"));
                PropertyInfo primaryKey = type.GetPropertiesWithkey();
                _findOneSql = $@"select   {colomn}
                                from {type.GetMappingName()}  where {primaryKey.Name}=@Id";
            }
            //insert
            {
                Type type = typeof(T);
                string colomn = string.Join(",", type.GetPropertiesWithNokey().Select(p => $"[{p.GetMappingName()}]"));
                string colomnParam = string.Join(",", type.GetPropertiesWithNokey().Select(p => $"@{p.GetMappingName()}"));
                _insertOneSql = $@"insert into {type.GetMappingName()} ({colomn}) values({colomnParam}))";
            }
            //update
            {
                Type type = typeof(T);
                string colomn = string.Join(",", type.GetPropertiesWithNokey().Select(p => $"[{p.GetMappingName()}]=@{p.GetMappingName()}"));
                PropertyInfo primaryKey = type.GetPropertiesWithkey();
                _updateOneSql = $@"update    {type.GetMappingName()} set  {colomn} where {primaryKey.Name}=Id";
            }
            //delete
            {
                Type type = typeof(T); 
                PropertyInfo primaryKey = type.GetPropertiesWithkey();
                _updateOneSql = $@"delete from    {type.GetMappingName()}  where  where {primaryKey.Name}=Id";
            }
        }
        public static string GetSql(SqlCacheBuilderType type)
        {
            switch (type)
            {
                case SqlCacheBuilderType.InsertOne:
                    return _insertOneSql;

                case SqlCacheBuilderType.FindOne:
                    return _findOneSql;
                case SqlCacheBuilderType.UpdateOne:
                    return _updateOneSql;
                case SqlCacheBuilderType.DeleteOne:
                    return _deleteOneSql;
                default:
                    return "";

            }
        }
    }
    public enum SqlCacheBuilderType
    {
        InsertOne,
        FindOne,
        UpdateOne,
        DeleteOne
    }
}
